package com.magupe.push.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.magupe.push.common.protocol.request.RPCMessageRequestPacket;
import com.magupe.push.common.protocol.response.RPCMessageResponsePacket;
import com.magupe.push.log.util.LogUtils;
import com.magupe.push.server.utils.SessionUtil;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class RPCMessageRequestHandler extends SimpleChannelInboundHandler<RPCMessageRequestPacket>{

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
    protected void channelRead0(ChannelHandlerContext ctx, RPCMessageRequestPacket packet) {
    	/**
    	 * 获取移动端用户的channel，并验证其是否有效
    	 */
    	String userId = packet.getUserId();
    	Channel userChannel = SessionUtil.getChannel(userId);
    	
    	if(userChannel != null && SessionUtil.hasLogin(userChannel)) {
        	/**
        	 * 发送消息到clientsdk端（移动端），通知clientsdk端有消息
        	 */
    		RPCMessageResponsePacket messageResponsePacket = new RPCMessageResponsePacket();
        	messageResponsePacket.setSuccess(true);
        	messageResponsePacket.setMessage(packet.getMessage());
        	messageResponsePacket.setUserId(packet.getUserId());
        	messageResponsePacket.setVersion(packet.getVersion());
        	
        	LogUtils.processLog(ctx.channel(), messageResponsePacket, "转发推送消息", false, null);
        	
    		userChannel.writeAndFlush(messageResponsePacket);
    	}
    	
    	logger.info("发送消息到rpc");
    	
    	/**
    	 * 发送消息到client端，通知client端消息发送成功
    	 */
    	RPCMessageResponsePacket response = new RPCMessageResponsePacket();
    	response.setSuccess(true);
    	response.setMessage("rpc ok");
    	ctx.channel().writeAndFlush(response);
    }

}
